package ioc06;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * IoC容器工具，用于获取Spring容器中的Bean
 */
public class ApplicationContextHolder  implements ApplicationContextAware {

    private static ApplicationContext ac;

    /**
     * 会自动注入当前的IoC容器
     */
    @Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        this.ac = ac;
    }

    /**
     * 根据名称获取Bean
     */
    public static Object getBean(String name) {
        return ac.getBean(name);
    }

    /**
     * 根据类型获取Bean
     */
    public static <T> T getBean(Class<T> clazz) {
        return ac.getBean(clazz);
    }
}
